package network2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket = null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        socket = new Socket(serverIp,serverPort);
    }
    public void start(){
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        try(InputStream inputStream = socket.getInputStream();
            Scanner scannnerNetwork = new Scanner(inputStream);

            OutputStream outputStream = socket.getOutputStream()){
            while(true){
//                1.从控制台读取数据
                System.out.print("请输入需要发送的数据：");
                String request = scanner.next();
                request += "\n";
//                2.把请求发送给服务器
                outputStream.write(request.getBytes());
//                3.从服务器读取响应
                if (!scannnerNetwork.hasNext()){
                    break;
                }
//                4.把响应显示到控制台
                String response = scannnerNetwork.next();
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1",9999);
        tcpEchoClient.start();
    }
}
